package com.eshore.mq.Mqtt;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author ZhouXiong
 * @Description
 * @apiDefine Created by ZhouX on 2021/9/6
 */
@Slf4j
@Configuration
public class MqttClientConfig {

    /**
     * 客户端ID
     */
    private final String clientId = "PUSH" + (int) (Math.random() * 100000000);

    /**
     * Mqtt客户端
     */
    private MqttClient mqttClient;


    @Autowired
    MqttClientInfo mqttClientInfo;

    @Bean
    public MqttClient mqttClient() throws MqttException {
        // 客户端创建
        setMqttClient(new MqttCallBack(), mqttClientInfo.getUrl(), mqttClientInfo.getUserName(),
                mqttClientInfo.getPassword());
        return this.mqttClient;
    }

    /**
     * 创建客户端
     *
     * @param mqttCallback 回调函数
     */
    public void setMqttClient(MqttCallback mqttCallback, String url, String userName, String password) throws
            MqttException {
        MqttConnectOptions options = mqttConnectOptions(url, userName, password);
        if (mqttCallback == null) {
            mqttClient.setCallback(new MqttCallBack());
        } else {
            mqttClient.setCallback(mqttCallback);
        }
        mqttClient.connect(options);
    }

    /**
     * 连接客户端
     */
    private MqttConnectOptions mqttConnectOptions(String url, String userName, String password) throws MqttException {
        mqttClient = new MqttClient(url, clientId, new MemoryPersistence());
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName(userName);
        options.setPassword(password.toCharArray());
        // 设置超时时间 单位为秒
        options.setConnectionTimeout(60);
        // 断开重连
        options.setAutomaticReconnect(true);
        options.setCleanSession(false);
        return options;
    }
}
